#!/usr/bin/perl -w
#
# Restore the content of a record from its log entry
#

use strict;

use Counter;
use FileTable;
use Getopt::Long;
use Algorithm::Diff;


use vars qw{$file $recno $rec $table $field $generation $seqno @data};

#GetOptions(
#	   );


$file = shift(@ARGV);
$recno = shift(@ARGV);
$generation = shift(@ARGV);

$table = Counter::openfile("$file");

$rec = $table->get($recno);
if (!$rec) {
    warn "$file: Record number $recno not found\n";
} else {

    print "==== $file record $recno ====\n";
    for my $key (sort($rec->fields())) {
	my $val = $$rec{$key};
	$val =~ s/\n/\n    /g;
	print "$key:$val\n" unless $key =~ /^\*/;
    }
}
print "----- History ----\n";
my ($ev, $field);
my (@hist, %save);
@hist = FileTable::Log::history($file, $recno);
for $ev (@hist) {
    $$ev{date} = ".undated" if !$$ev{date};
}
$seqno = 0;
for $ev (sort {$$a{date} cmp $$b{date}} @hist) {
    ++ $seqno;
    $data[$seqno] = $$ev{data};
    print "[$seqno] $$ev{date}: $$ev{tablename} ($$ev{operation} $$ev{authority})\n";
    printdiff($save{$$ev{tablename}}, $$ev{data}); 
    $save{$$ev{tablename}} = $$ev{data};
    print "\n";
}

if ($generation) {
    warn "Restoring version $generation\n";
} else {
    warn "Restoring version $seqno (last)\n";
    $generation = $seqno;
}
if ($data[$generation]) {
    my $newrec = $table->makeobject($recno, $data[$generation]);
    print "==== $file record $recno ====\n";
    for my $key (sort($newrec->fields())) {
	my $val = $$newrec{$key};
	$val =~ s/\n/\n    /g;
	print "$key:$val\n" unless $key =~ /^\*/;
    }
    $newrec->store();
} else {
    die "No data for generation $generation\n";
}




sub printdiff {
    my ($old, $new) = @_;

    if (!$old) {
	$new =~ s/(^|\n)/$1N /g;
	print $new;
    } else {
	my @old = sort(split(/\n/, $old));
	my @new = sort(split(/\n/, $new));
	my @diffs = Algorithm::Diff::diff(\@old, \@new);
	my $hunk;
	for $hunk (@diffs) {
	    my $chg;
	    for $chg (@$hunk) {
		next if $$chg[2] =~ /^f_mtime/; # superfluous
		print $$chg[0], " ", $$chg[2], "\n",
	    }
	}
    }
}
